"""
des: rename处理拓展MiXin
author: mr_52hz
date: 2021-02-03
"""
import os
import re


class ReNameFuncMixin(object):

    """
    Mixin方法中的参数保持结构一致
    """

    def replace(self, origin, target, path, file, run=False):
        new_file = file.replace(origin, target)
        self.rename(os.path.join(path, file), os.path.join(path, new_file), run)
        return new_file

    def addPrefix(self, prefix, _, path, file, run=False):
        p, n = os.path.split(file)
        new_file = os.path.join(p, prefix+n)
        self.rename(os.path.join(path, file), os.path.join(path, new_file), run)
        return new_file

    def addSuffix(self, suffix, _, path, file, run=False):
        p, n = os.path.split(file)
        name, extension = os.path.splitext(n)
        new_file = os.path.join(p, name+suffix+extension)
        self.rename(os.path.join(path, file), os.path.join(path, new_file), run)
        return new_file

    def changeFormat(self, origin, target, path, file, run=False):
        p, extension = os.path.splitext(file)
        new_file = p + '.' + target
        if origin == extension:
            self.rename(os.path.join(path, file), os.path.join(path, new_file), run)
        return new_file

    def delete(self, origin, target, path, file, run=False):
        # 不能将文件名全部删除
        if origin == file:
            return file

        new_file = self.replace(origin, '', path, file, run=run)

        # 不能只有后缀
        if new_file.startswith('.') and new_file.count('.') == 1:
            return file
        return new_file

    def rename(self, src, desc, run=False):
        # 名字相同 跳过
        if src == desc:
            return

        if run:
            idx = 0
            while not self._rename(src, desc, idx):
                idx += 1

    def re(self, pattern, repl, path, file, run=False):

        new_file_name = re.sub(pattern, repl, file, count=1)
        self.rename(os.path.join(path, file), os.path.join(path, new_file_name), run=run)
        return new_file_name

    def reZeroFill(self, pattern, repl, path, file, run=False):
        # re.match pattern使用全匹配 suffix中保留一个特征pre_str
        res = re.match(pattern, file)
        if res is None:
            return file
        res_dict_keys = list(res.groupdict().keys())
        if len(res_dict_keys) != 1:
            return file
        fix_str = res[res_dict_keys[0]]
        if fix_str[0].isdigit():
            pre_str, num = fix_str[-1], fix_str[:-1]
        else:
            pre_str, num = fix_str[0], fix_str[1:]
        if len(num) < int(repl):
            if fix_str[0].isdigit():
                _fix_str = num.zfill(int(repl)) + pre_str
            else:
                _fix_str = pre_str + num.zfill(int(repl))
            new_file = re.sub(fix_str, _fix_str, file, count=1)
            self.rename(os.path.join(path, file), os.path.join(path, new_file), run)
            return new_file
        return file

    @staticmethod
    def _rename(src, desc, idx):
        try:
            if idx > 0:
                pre, extension = os.path.splitext(desc)
                desc = pre + '-(%s)' % idx + extension
            os.rename(src, desc)
            return True
        except FileExistsError:
            return False
